from pydantic import BaseModel

# coding: utf-8
from sqlalchemy import BigInteger, CHAR, Column, DateTime, Integer, String, event, ForeignKey
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship
from sqlalchemy.sql import func
from datetime import datetime
from typing import Optional
from models.base import Base

metadata = Base.metadata


class SysDept(Base):
    def to_dict(self):
        dept_dict = {c.name: getattr(self, c.name) for c in self.__table__.columns}

        for key, value in dept_dict.items():
            if isinstance(value, datetime):
                dept_dict[key] = value.isoformat()

        return dept_dict

    __tablename__ = 'sys_depts'

    id = Column(BigInteger, primary_key=True, comment='部门id')
    parent_id = Column(BigInteger, ForeignKey('sys_depts.id'), comment='父部门id')
    ancestors = Column(String(50, 'utf8mb4_unicode_ci'), comment='祖级列表')
    dept_name = Column(String(30, 'utf8mb4_unicode_ci'), comment='部门名称')
    order_num = Column(Integer, comment='显示顺序')
    leader = Column(String(20, 'utf8mb4_unicode_ci'), comment='负责人')
    phone = Column(String(11, 'utf8mb4_unicode_ci'), comment='联系电话')
    email = Column(String(50, 'utf8mb4_unicode_ci'), comment='邮箱')
    status = Column(CHAR(1, 'utf8mb4_unicode_ci'), comment='部门状态（0正常 1停用）')
    del_flag = Column(CHAR(1, 'utf8mb4_unicode_ci'), comment='删除标志（0代表存在 2代表删除）')
    create_by = Column(String(64, 'utf8mb4_unicode_ci'), comment='创建者')
    update_by = Column(String(64, 'utf8mb4_unicode_ci'), comment='更新者')
    created_at = Column(DateTime(timezone=True), server_default=func.now(), comment='创建时间')
    updated_at = Column(DateTime(timezone=True), onupdate=func.now(), comment='更新时间')
    deleted_at = Column(DateTime, comment='删除时间')
    children = relationship('SysDept', backref='parent', remote_side=[id])
    users = relationship("SysUser", back_populates="dept")


@event.listens_for(SysDept, 'before_update')
def receive_before_update(mapper, connection, target):
    target.updated_at = datetime.strftime(datetime.now(), "%Y-%m-%d %H:%M")

@event.listens_for(SysDept, 'before_insert')
def set_created_at(mapper, connection, target):
    if not target.created_at:
        target.created_at = datetime.strftime(datetime.now(), "%Y-%m-%d %H:%M")



class SysDeptSchema(BaseModel):
    id: int
    parent_id: int
    ancestors: str
    dept_name: str
    order_num: int
    leader: str
    phone: str
    email: str
    status: str
    del_flag: str
    create_by: str
    update_by: str
    created_at: Optional[datetime] = None
    updated_at: Optional[datetime] = None
    deleted_at: Optional[datetime] = None

    class Config:
        orm_mode = True
        json_encoders = {
            datetime: lambda v: v.strftime('%Y-%m-%d %H:%M:%S') if v else None
        }
        from_attributes = True
